package com.lenovo.rc.sil.wangdwa.learning;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BroadcastRecieverDemoActivity extends Activity implements OnClickListener{
    public static final String INTENT_EXTRAS_NAME = "BroadcastRecieverDemoActivity";
    
	private DummyBroadcastReceiver receiver = null;
	private IntentFilter filter = null;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnRegister = (Button)findViewById(R.id.register);
        btnRegister.setOnClickListener(this);
        Button btnSend = (Button)findViewById(R.id.send);
        btnSend.setOnClickListener(this);
        
        receiver = new DummyBroadcastReceiver();
        filter = new IntentFilter(DummyBroadcastReceiver.class.getName());
        
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.register:
			doRegister();
			break;
		case R.id.send:
			doSend();
			break;
		}
		
	}
	
	
	

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(receiver != null) {
			this.unregisterReceiver(receiver);
		}
		super.onDestroy();
	}

	private void doSend() {
		// TODO Auto-generated method stub
		Log.d(this.getClass().getName(), "entering doSend()");
		
//		Intent sendIntent = new Intent(this, DummyBroadcastReceiver.class);
		// the Intent is different when used in BroadcastReceiver
		Intent sendIntent = new Intent(DummyBroadcastReceiver.class.getName());
		sendIntent.putExtra(INTENT_EXTRAS_NAME, INTENT_EXTRAS_NAME);
		this.sendBroadcast(sendIntent);
	}

	private void doRegister() {
		// TODO Auto-generated method stub
		Log.d(this.getClass().getName(), "entering doRegister()");
		
		this.registerReceiver(receiver, filter);
	}
}